package com.aaa.sso.util;

import com.aaa.common.bo.Member;
import com.aaa.common.util.Result;
import com.aaa.sso.service.RemoteMemberService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Xiujie Yu
 * @Date 2021-01-21
 * @Time 16:47
 */
public class MemberRealm extends AuthorizingRealm {

    @Autowired
    private RemoteMemberService remoteMemberService;

    /**
     * 功能描述:授权
     * @param principalCollection PrincipalCollection
     * @return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 功能描述:认证
     * @param authenticationToken AuthenticationToken
     * @return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        //获取用户名
        String userName = (String) authenticationToken.getPrincipal();
        Result<Member> result = remoteMemberService.getMemberByUserName(userName);
        Member member = result.getT();
        if (member==null){
            //用户不存在
            throw new AccountException();
        }
        //参数解释：登录后会员信息  加密密码  盐值的自己解数组对象  当前验证对象的名称
        return new SimpleAuthenticationInfo(member,member.getPassword(), ByteSource.Util.bytes(member.getPwSalt()),member.getPhoneNum());
    }


}
